package meta.api.web.image.presentation;

import java.util.Date;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import meta.api.web.account.businessinfo.UserInfo;
import meta.api.web.common.util.ApiConst;
import meta.api.web.common.util.ApiUtil;
import meta.api.web.file.businessinfo.FileInfo;
import meta.api.web.file.businessinfo.MetadataInfo;
import meta.api.web.image.businesscontrol.ImageMngBusiCtrl;
import meta.common.log.CmnLogger;
import meta.common.msg.MessageConst;
import meta.common.util.DateUtil;
import meta.common.util.JsonUtil;
import meta.common.util.StrUtil;
import meta.common.util.WebUtil;

@Controller
@RequestMapping(value="api/image")
@Tag(name = "图片管理机能", description = "图片管理机能")
public class ImageMngController {

    private static final CmnLogger logger = CmnLogger.getLogger(ImageMngController.class);

    private static final String FUNC_NM = "图片管理机能";

    private static final String ERROR_MSG_SAVE_ERROR= "保存图片失败";
    private static final String ERROR_MSG_GET_ERROR= "获取图片失败";
    private static final String ERROR_MSG_DELETE_ERROR= "删除图片失败";

    @Autowired
    private ImageMngBusiCtrl imageMngBusiCtrl;

    /**
     * 上传图片
     * 
     * @param req 请求
     * @param res 响应
     * @param file 文件
     * @param filename 文件名
     * @param tags 标签
     * @param share 是否共享
     * @param directory 文件目录
     * @param remarks 备注
     * @return
     * @throws Exception 异常
     */
    @PostMapping(value="/upload")
    @Operation(tags = "上传图片", description = "上传图片")
    public String upload(HttpServletRequest req, HttpServletResponse res,
            @RequestParam(value = "file", required = true) MultipartFile file,
            @RequestParam(value = "filename", required = false) String filename,
            @RequestParam(value = "tags", required = false) String tags,
            @RequestParam(value = "share", required = false) boolean share,
            @RequestParam(value = "directory", required = false) String directory,
            @RequestParam(value = "remarks", required = false) String remarks) throws Exception {
        ApiUtil.callApiLog(req, FUNC_NM, "上传图片", null);

        // 取得登录用户详细情报
        UserInfo loginUser = WebUtil.getLoginUser(req);

        if (StrUtil.isEmpty(filename)) {
            filename = file.getOriginalFilename();
        }

        String newfilename = loginUser.getId() + "_" + DateUtil.toStrForDwMs(new Date()) + "_" + filename;

        FileInfo inputFileInfo = new FileInfo();
        // 文件名
        inputFileInfo.setFilename(newfilename);
        // URL
        inputFileInfo.setUrl("/api/image/" + newfilename);
        // 字节长度
        inputFileInfo.setLength(file.getSize());
        // 元数据
        MetadataInfo metadata = new MetadataInfo();
        metadata.setName(filename);
        metadata.setTags(tags);
        metadata.setShared(share);
        metadata.setDirectory(directory);
        metadata.setRemarks(remarks);
        metadata.setType(ApiConst.FILE_TYPE_IMG);
        metadata.setUserid(loginUser.getId());
        inputFileInfo.setMetadata(metadata);

        // 保存图片
        try {
            imageMngBusiCtrl.saveImg(inputFileInfo, file.getBytes());
        } catch (Exception e) {
            logger.log(MessageConst.MSG_01090001, null, e);
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_SAVE_ERROR);
            return null;
        }

        // 获取图片信息
        FileInfo outputFileInfo = imageMngBusiCtrl.getImgByFilename(newfilename, loginUser.getId());
        if (outputFileInfo == null) {
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_GET_ERROR);
            return null;
        }

        ApiUtil.setJsonResponse(res, JsonUtil.toJsonStr(outputFileInfo));
        return null;
    }

    /**
     * 获取图片
     * 
     * @param req 请求
     * @param res 响应
     * @param path 文件路径
     * @return
     * @throws Exception 异常
     */
    @GetMapping(value="/{path}")
    @Operation(tags = "获取图片", description = "获取图片")
    public String getImg(HttpServletRequest req, HttpServletResponse res,
            @PathVariable("path") String path) throws Exception {
        ApiUtil.callApiLog(req, FUNC_NM, "获取图片", null);

        // 取得登录用户详细情报
        UserInfo loginUser = WebUtil.getLoginUser(req);

        // 取得图片情报
        FileInfo outputFileInfo = imageMngBusiCtrl.getImgByFilename(path, loginUser.getId());
        if (outputFileInfo == null) {
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_GET_ERROR);
            return null;
        }

        // output
        WebUtil.outputBin(res, outputFileInfo.getFilename(), outputFileInfo.getFileContent());
        return null;
    }

    /**
     * 删除图片
     * 
     * @param req 请求
     * @param res 响应
     * @param path 文件路径
     * @return
     * @throws Exception 异常
     */
    @DeleteMapping(value="/{path}")
    @Operation(tags = "删除图片", description = "删除图片")
    public String deleteImg(HttpServletRequest req, HttpServletResponse res,
            @PathVariable("path") String path) throws Exception {
        ApiUtil.callApiLog(req, FUNC_NM, "删除图片", null);

        // 取得登录用户详细情报
        // UserInfo loginUser = WebUtil.getLoginUser(req);

        // 权限检证
        // if (!imageMngBusiCtrl.checkIsFileOwner(path, loginUser.getId())) {
        //     ApiUtil.setForbiddenResponse(req, res);
        //     return null;
        // }

        // 删除图片
        try {
            imageMngBusiCtrl.deleteImgByFilename(path, null);
            ApiUtil.setEmptyJsonResponse(res);
        } catch (Exception e) {
            logger.log(MessageConst.MSG_01090001, null, e);
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_DELETE_ERROR);
        }

        return null;
    }
}
